<template>


    <div style="display:flex;flex-direction:column;justify-content:center;align-items:center;">

        <el-card class="layout-container">
            <template #header>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <h3 v-if="courseDetail && courseDetail.task_name"> {{ courseDetail.task_name }}
                        </h3>
                    </div>
                    <div>

                        <el-button v-if="$store.state.user.is_teacher && !is_editing" type="primary" circle
                            @click.stop="handleTeacherEditTask">
                            <svg t="1713083812819" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                xmlns="http://www.w3.org/2000/svg" p-id="4184" width="15" height="15">
                                <path
                                    d="M652.4 156.6125a112.5 112.5 0 1 1 155.925 161.15625L731.375 394.71875 572.3 235.5875l79.5375-79.5375 0.5625 0.5625zM333.63125 792.40625v0.1125H174.5v-159.1875l358.03125-357.975 159.075 159.13125-357.975 357.91875zM62 849.5h900v112.5H62v-112.5z"
                                    fill="#FFFFFF" p-id="4185"></path>
                            </svg>
                        </el-button>
                        <el-button v-if="$store.state.user.is_teacher && !is_editing" type="danger" circle
                            @click.stop="handleDeleteTask">
                            <svg t="1713084447474" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                xmlns="http://www.w3.org/2000/svg" p-id="5629" width="15" height="15">
                                <path
                                    d="M853.333333 192v42.666667a21.333333 21.333333 0 0 1-21.333333 21.333333h-640a21.333333 21.333333 0 0 1-21.333333-21.333333v-42.666667a21.333333 21.333333 0 0 1 21.333333-21.333333H384V128a42.666667 42.666667 0 0 1 42.666667-42.666667h170.666666a42.666667 42.666667 0 0 1 42.666667 42.666667v42.666667h192a21.333333 21.333333 0 0 1 21.333333 21.333333zM250.453333 859.306667a85.333333 85.333333 0 0 0 85.333334 79.36h353.28a85.333333 85.333333 0 0 0 85.333333-79.36L810.666667 341.333333H213.333333z"
                                    p-id="5630" fill="#ffffff"></path>
                            </svg> </el-button>

                        <el-button type="primary" round size="large" @click="$router.back()">返回</el-button>
                    </div>
                </div>

            </template>

            <div style="display: flex;flex-direction: column; ">

                <div v-if="courseDetail && !is_editing"
                    style="display: flex; flex-direction: column; align-items: center;">
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <el-descriptions title="基本信息" size="large" border :column="1">
                                <el-descriptions-item v-for="row in infoRows" :label="row.label">
                                    {{ courseDetail[row.field] }}
                                </el-descriptions-item>
                            </el-descriptions>

                            <el-descriptions size="large" border :column="1">

                                <el-descriptions-item label="任务资源" width="200px">
                                    <div class="info_row_right" v-if="existingFiles.length > 0">
                                        <div style=" color: #666;" v-for="(file, index) in existingFiles" :key="index">
                                            <el-link type="primary" :underline="false"
                                                @click.stop="downloadTeachingSourceFile(file)">
                                                {{ index + 1 }}、{{ file }}
                                            </el-link>

                                        </div>
                                    </div>
                                    <div class="info_row_right" v-else>
                                        暂无资源<span v-if="$store.state.user.is_teacher">，请<el-button type="primary"
                                                style="margin-bottom: 2px;" link @click.stop="is_editing = true">
                                                编辑{{ task_title }}</el-button>添加{{ task_title }}材料</span>
                                    </div>
                                </el-descriptions-item>
                                <el-descriptions-item :label="`${task_title}描述`">
                                    {{ courseDetail.description }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                        <el-col :span="10">
                            <div class="info_row_left">
                                <h4>完成情况</h4>
                            </div>
                            <DoTaskEmailBtn v-if="$store.state.user.is_teacher" :course_id="form.course_id"
                                :task_id="String(form.task_id)" />

                            <SubmitLoop :course_id="form.course_id" :task_id="String(form.task_id)" />
                        </el-col>
                    </el-row>
                    <div class="info_row" style="margin-top: 20px;">
                        <el-button size="default" v-if="!$store.state.user.is_teacher" type="primary"
                            :disabled=enterBtnDisabled @click.stop="handleEnterTaskContainer">在线实验</el-button>
                    </div>

                </div>
                <el-divider />
                <div v-if="!$store.state.user.is_teacher">

                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div v-if="form.task_type !== 'exam'">

                                <span>
                                    <UploadFiles :btnDisabled=enterBtnDisabled :existingFiles="existingFiles"
                                        @update:stuFileList="handleStuFileListUpdate" />
                                    <!-- 当学生作业列表不为空，那么显示确定提交按钮，否则不显示 -->
                                </span>
                                <el-button :disabled="enterBtnDisabled" v-if="stuFileList.length > 0" type="primary"
                                    @click="handleUploadStudentFiles">确定提交</el-button>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <!-- 如果没有提交，stuSubmittedFileList的大小为0，那么显示暂未提交 -->
                            <div v-if="stuSubmittedFileList.length == 0">
                                暂未提交
                            </div>



                            <div v-else
                                style="font-size: 12px; color: #666; display: flex; align-items: center; margin:2px"
                                v-for="(file, index) in stuSubmittedFileList" :key="index">
                                <span> {{ index + 1 }}、 {{ file }}：</span>
                                <el-button :disabled=enterBtnDisabled type="danger" size="small" round
                                    style="align-content: right;font-size: 12px;height:18px"
                                    @click="handleDeleteStuTask(file)">删除</el-button>

                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div>
                                分数
                            </div>
                            <div>
                                {{ task_score }}
                            </div>
                        </el-col>
                    </el-row>




                </div>

                <div v-if="is_editing" style="display: flex; flex-direction: column; align-items: center;">

                    <div class="info_row">
                        <div class="info_row_left">{{ task_title }}名称：</div>
                        <div class="info_row_right">
                            <el-input v-model="courseDetail.task_name" :placeholder="`请输入${task_title}名称`" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">相关资源：</div>
                        <div class="info_row_right">
                            <UploadFiles ref="childComponent" :btnDisabled=btnDisabled :existingFiles=existingFiles
                                :is_creating_task=false @update:fileList="handleFileListUpdate" />
                                <div style="margin-top: 20px;" v-if="existingFiles.length > 0">
                            <div  style="font-size: 12px; color: #666; " v-for="(file, index) in existingFiles"
                                :key="index">
                                {{ index + 1 }}、 {{ file }}
                                <el-button type="danger" size="small" round
                                    @click="handleDeleteTeachingSourceFile(file)">删除</el-button>
                            </div></div>
                        </div>
                    </div>
                    <div class="info_row">
                        <div class="info_row_left">开始时间：</div>
                        <div class="info_row_right">
                            <el-date-picker type="datetime" placeholder="选择开始时间" size="default" clearable
                                v-model="courseDetail.start_time" />
                        </div>
                    </div>



                    <div class="info_row">
                        <div class="info_row_left">结束时间：</div>
                        <div class="info_row_right">
                            <el-date-picker type="datetime" placeholder="选择截止时间" size="default" clearable
                                v-model="courseDetail.end_time" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">{{ task_title }}描述：</div>
                        <div class="info_row_right">
                            <el-input type="textarea" v-model="courseDetail.description"
                                :placeholder="`请输入${task_title}描述`" />
                        </div>
                    </div>

                    <div class="info_row">
                        <div class="info_row_left">{{ task_title }}总分：</div>
                        <div class="info_row_right">
                            <el-input type="number" v-model="courseDetail.score" :placeholder="`请输入${task_title}总分`" />
                        </div>
                    </div>

                    <div class="info_row">
                        <el-button type="primary" @click="handleSaveEditTask">保存</el-button>

                        <el-button type="primary" @click="handleCancelEditTask">取消</el-button>
                    </div>

                </div>

            </div>

        </el-card>

        <TaskStuList v-show="!is_editing" v-if="$store.state.user.is_teacher" :course_id="form.course_id"
            :task_id="form.task_id" />

    </div>


</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { getTaskScoreApi } from '@/api/course'
import { getTaskDetailApi, submitTaskApi, getSubmittedTaskFilesApi, updateTaskApi, deleteStuTaskFileApi, deleteTeaTaskFileApi, setTaskFilesApi, getTaskFilesApi } from '@/api/task';
import { goTaskContainerApi } from '@/api/clusterManagement'
import UploadFiles from "@/views/main/public/publicKit/uploadFiles.vue";
import type { UploadProps } from 'element-plus'
import TaskStuList from "./taskStuList.vue"
import SubmitLoop from './taskLoopPic.vue'
import DoTaskEmailBtn from "@/views/main/teacher/forms/sendDoTaskEmailButton.vue"
import { downloadTeaFile } from '@/views/main/task/downloadFile'
const childComponent = ref(null);
const callChildMethod = (params: any) => {
    if (childComponent.value) {
        childComponent.value.childMethod(params);
    }
};
onMounted(() => {
    infoRows.value = [
        { label: '班课名称', field: 'course_name' },
        { label: `${task_title.value}ID`, field: 'task_id' },
        { label: `${task_title.value}名称`, field: 'task_name' },
        { label: '开始时间', field: 'start_time' },
        { label: `${task_title.value}总分`, field: 'score' },
        { label: '结束时间', field: 'end_time' },
        { label: '学生总数', field: 'stu_count' }

    ];
    const queryForm = {
        course_id: history.state.course_id,
        task_id: history.state.task_id,
        user_id: store.state.user.user_id,
        is_teacher: store.state.user.is_teacher,
        token: store.state.user.token,
    }
    btnDisabled.value = history.state.btnDisabled;

    getTaskDetailApi(queryForm).then((res: any) => {
        if (res.code === 200) {
            courseDetail.value = res.data;

            if (courseDetail.value.start_time_raw - 5 * 60 * 1000 > new Date().getTime() || courseDetail.value.end_time_raw < (new Date().getTime())) {
                enterBtnDisabled.value = true;
            } else {
                enterBtnDisabled.value = false;
            }
            if (courseDetail.value.score_published) {
                enterBtnDisabled.value = true;
                // btnDisabled.value = true;
            }
        } else {
            ElMessage.error(res.message);
        }
    })
    getTaskFilesApi({ task_id: history.state.task_id, task_type: form.value.task_type, course_id: history.state.course_id }).then((res: any) => {
        if (res.code === 200) {
            existingFiles.value = res.data;
        }
    })
    // 如果是学生，查找已经提交的作业的文件
    if (!store.state.user.is_teacher) {
        getSubmittedTaskFilesApi({ task_id: history.state.task_id, user_id: store.state.user.user_id }).then((res: any) => {
            if (res.code === 200) {
                stuSubmittedFileList.value = res.data;
            }
        })
    }
    getTaskScoreApi({ task_id: history.state.task_id, user_id: store.state.user.user_id }).then((res: any) => {
        if (res.code === 200) {
            task_score.value = res.data;
        }
    })
});


const infoRows = ref([])
const store = useStore()
const router = useRouter()
const btnDisabled = ref(false)
const enterBtnDisabled = ref(false)
const form = ref({
    course_id: history.state.course_id,
    task_id: history.state.task_id,
    task_type: history.state.task_type,
    is_teacher: store.state.user.is_teacher,
    user_id: store.state.user.user_id,
    token: store.state.user.token,
});
const task_title = ref(history.state.task_type === 'homework' ? '作业' : history.state.task_type === 'exam' ? '考试' : '实验')
const task_score = ref(null)
const is_editing = ref(false);
const existingFiles = ref([]);
const courseDetail = ref(null);
const handleTeacherEditTask = () => {
    is_editing.value = !is_editing.value;

};
const fileList = ref([])
const stuFileList = ref([])
const stuSubmittedFileList = ref([])
const handleDeleteTeachingSourceFile = (file: any) => {
    ElMessageBox.confirm(`确认删除${file}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        deleteTeaTaskFileApi({
            task_id: courseDetail.value.task_id,
            file_name: file,
            task_type: form.value.task_type,
            course_id: form.value.course_id,
        }).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('删除成功')
                existingFiles.value = existingFiles.value.filter((item: any) => item !== file)
            }
        })
    })
}
const handleDeleteTask = () => {
    ElMessageBox.prompt(`请输入任务名称确认删除(学生之前提交的${task_title.value}记录也会删除)`, '删除提示', {
        confirmButtonText: '删除',
        confirmButtonClass: 'el-button--danger',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(({ value }) => {
        if (value === courseDetail.value.task_name) {
            deleteTeaTaskFileApi({
                task_id: courseDetail.value.task_id,
                file_name: courseDetail.value.task_name,
            }).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    router.push('/teacher/home')
                }
            })
        } else {
            ElMessage.error(`请输入正确的${task_title.value}名称`)
        }
    })
}
const handleFileListUpdate = (newFileList: any) => {
    // 更新父组件中的 existingFiles
    fileList.value = newFileList;
};

const handleStuFileListUpdate = (newFileList: any) => {
    // 更新父组件中的 existingFiles
    stuFileList.value = newFileList;
};

const handleTeacherDeleteFile = (row: any) => {
    ElMessageBox.prompt(`请输入任务名称确认删除(学生之前提交的${task_title.value}记录也会删除)`, '删除提示', {
        confirmButtonText: '删除',
        confirmButtonClass: 'el-button--danger',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(({ value }) => {
        if (value === courseDetail.value.task_name) {
            const tempForm = ref({
                task_id: courseDetail.value.task_id,
                user_id: store.state.user.user_id,
                is_teacher: store.state.user.is_teacher,
                course_id: form.value.course_id,
                task_type: form.value.task_type,
                file_name: row.file_name,
            })
            deleteTeaTaskFileApi(tempForm.value).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    // router.push('/teacher/home')
                }
            })
        } else {
            ElMessage.error(`请输入正确的${task_title.value}名称`)
        }
    })
}
const handleEnterTaskContainer = () => {
    if (store.state.user.isMobile) {
        ElMessage.warning('请在PC端完成实验');
        return;
    }

    const loadingInstance = ElLoading.service({ text: `正在进入${task_title.value}容器，首次加载时间较长，请耐心等待...`, fullscreen: true })

    goTaskContainerApi({
        course_id: form.value.course_id,
        task_id: form.value.task_id,
        is_teacher: store.state.user.is_teacher,
        user_id: store.state.user.user_id,
        task_type: form.value.task_type,
    }).then((res: any) => {
        loadingInstance.close();
        if (res.code === 200) {
            const url = res.data.url;
            ElMessage.success(`加载${task_title.value}容器成功`);
            router.push({
                name: 'studentTask',
                state: {
                    url: url,
                    title: courseDetail.value.task_name,
                    task_type: form.value.task_type,
                    task_id: courseDetail.value.task_id,
                    course_id: form.value.course_id
                }
            });
        } else {
            ElMessage.error(res.message);
        }
    }).finally(() => {
        loadingInstance.close();
    })
}
const handleSaveEditTask = () => {
    try {
        updateTaskApi(courseDetail.value).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('保存成功');
                // 清空文件列表
                // fileList.value = [];
                // 刷新页面
            }
        })

        if (fileList.value.length > 0) {
            callChildMethod({
                course_id: history.state.course_id,
                task_id: history.state.task_id,
                task_type: history.state.task_type,
            })

        } else {
            is_editing.value = false;
        }

    } finally {
        // is_editing.value = false;
    }
}
const handleDeleteStuTask = (file_name: string) => {
    ElMessageBox.confirm('确认删除该文件？').then(() => {

        const tempForm = ref({
            file_name: file_name,
            task_id: courseDetail.value.task_id,
            course_id: courseDetail.value.course_id,
            user_id: store.state.user.user_id,
            is_teacher: store.state.user.is_teacher,
            task_type: form.value.task_type,
        })
        deleteStuTaskFileApi(tempForm.value).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('文件删除成功');
                // 更新前端显示的文件列表
                existingFiles.value = existingFiles.value.filter(item => item !== file_name);
                location.reload();
            }
        })
    })
}
const downloadTeachingSourceFile = (file_name: string) => {
    downloadTeaFile(file_name, courseDetail.value.task_id)
}
const handleSubmitTask = () => {
    const tempForm = ref({
        task_id: courseDetail.value.task_id,
        course_id: courseDetail.value.course_id,
        user_id: store.state.user.user_id,
        file_name: null,
        file_content: null,
    })

}
const handleUploadStudentFiles = () => {
    const tempForm = ref({
        task_type: form.value.task_type,
        task_id: courseDetail.value.task_id,
        course_id: courseDetail.value.course_id,
        user_id: store.state.user.user_id,
        file_name: null,
        file_content: null,
    })
    for (const file of stuFileList.value) {
        const reader = new FileReader();
        // 定义文件读取完成时的回调函数
        reader.onload = (event) => {
            tempForm.value.file_name = file.name.toString();
            tempForm.value.file_content = event.target.result.toString();
            submitTaskApi(tempForm.value).then((res: any) => {
                if (res.code === 200) {
                    ElMessage.success('文件上传成功');
                    // 清空文件列表
                    stuFileList.value = [];
                    // 刷新页面
                    location.reload();
                }
            });
        };
        reader.readAsDataURL(file.raw);
    }

}
const handleCancelEditTask = () => {
    is_editing.value = false;
}



const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `删除上传文件 ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}



</script>

<style lang="scss" scoped>
.info-card {
    position: relative;
    width: 100vw;
    max-width: 1000px;
    height: auto;
    max-height: 800px;

    align-content: center;
    margin-top: 10px;
}



.info_row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
    vertical-align: auto;
    align-self: center;
}

.info_row_left {
    width: 10vw;
    min-width: 100px;
    text-align: left;
    font-size: large;
}

.info_row_right {
    width: 30vw;
    min-width: 220px;
    text-align: left;
    // font-size: large;

}
</style>